/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.invocation.client;

import org.nuxeo.gwt.habyt.invocation.client.events.EventBus;
import org.nuxeo.gwt.habyt.invocation.client.events.NotificationEvent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class Invoker {

    private static InvocationServiceAsync RPC = GWT.create(InvocationService.class);

    public static InvocationServiceAsync getService() {
        return RPC;
    }

    public static void invoke(final Invocation invocation) {
        invoke(invocation, null, true);
    }

    public static void invoke(final Invocation invocation,
            final InvocationCallback cb) {
        invoke(invocation, cb, false);
    }

    public static void invoke(final Invocation invocation,
            final InvocationCallback cb, boolean fireEvents) {
        RPC.invoke(invocation, new InvocationCallbackWrapper(invocation, cb,
                fireEvents));
    }

    static class InvocationCallbackWrapper implements InvocationCallback {
        protected InvocationCallback cb;

        protected Invocation invocation;

        protected boolean fireEvents;

        public InvocationCallbackWrapper(Invocation invocation,
                InvocationCallback cb, boolean fireEvents) {
            this.cb = cb;
            this.fireEvents = fireEvents;
        }

        @Override
        public void onSuccess(InvocationResponse result) {
            if (cb != null) {
                cb.onSuccess(result);
            }
            if (fireEvents) {
                EventBus.get().fireEvent(
                        new NotificationEvent(result, invocation));
            }
        }

        @Override
        public void onFailure(Throwable caught) {
            if (cb != null) {
                cb.onFailure(caught);
            } else {
                // TODO custom global error handler
                Window.alert(caught.getMessage());
            }
        }
    }
}
